import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import {Toast} from 'mint-ui'
import {logout} from "./utils/tool"
import admin from './router/admin'
import user from './router/user'
import room from './router/room'
import factory from './router/factory'

Vue.use(Router)

let router =  new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'home',
            // component: Home,
            redirect: {
                name: 'login'
            }
        },
        {
            path: '/login.html',
            name: 'login',
            component: resolve => require(['./views/login/index.vue'], resolve),
            meta: {
                title: '登录'
            }
        },
        {
            path: '/register.html',
            name: 'register',
            component: resolve => require(['./views/register/index.vue'], resolve),
            meta: {
                title: '注册用户'
            }
        },
        user,
        admin,
        room,
        factory
    ]
})

/**
 * 路由拦截器
 */
router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {
        let status = parseInt(sessionStorage.getItem('user_status'))
        if (sessionStorage.getItem('token') && status === 1) {
            let userType    = sessionStorage.getItem('user_type')
            let expireIn    = sessionStorage.getItem('expire_in')
            let timestamp3  = new Date().getTime()

            if (userType !== to.meta.userType && (to.meta.userType === 'all' && !userType)) {
                Toast('您没有访问该页面的权限，请与管理员联系')
                // 退出当前用户
                logout()
                next({
                    name: 'login'
                })
            } else if (expireIn < timestamp3){
                Toast('证书已过期，请重新登录')
                // 退出当前用户
                logout()
                next({
                    name: 'login'
                })
            } else {
                next()
            }
        } else {
            next({
                name: 'login',
                query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
            })
        }
    } else {
        next()
    }
})


export default router